<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('人天成本维护') }}</span>
    </div>
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container mb20">
          <el-input
            v-model="deptName"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            :placeholder="$t('部门名称')"
          />
        </div>
        <div v-loading="treeLoading" class="head-container" style="max-height: 560px;overflow: auto;">
          <el-tree
            v-if="type !== ''"
            ref="tree"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expand-all="type === 'tree'"
            :lazy="type !== 'tree'"
            :load="lazyLoad"
            node-key="id"
            :default-expanded-keys="expandedKeys"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item :label="$t('用户名称')" prop="userId">
            <UserSelect v-model="queryParams.userId" :placeholder="$t('用户名称')" />
          </el-form-item>
          <el-form-item :label="$t('月份')" prop="startDate">
            <el-date-picker
              v-model="queryParams.createTime"
              :clearable="false"
              style="width: 200px"
              type="month"
              value-format="yyyy-MM"
              :placeholder="$t('起始日期')"
            />
          </el-form-item>
          <el-form-item :label="$t('状态')" prop="status">
            <el-select
              v-model="queryParams.status"
              :placeholder="$t('请选择')"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['anxin:dailyCost:import']"
              type="info"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >{{ $t('导入') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['anxin:dailyCost:export']"
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="exportHandle"
            >{{ $t('导出') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['anxin:dailyCost:edit']"
              type="warning"
              icon="el-icon-edit"
              size="mini"
              @click="batchEditHandle"
            >{{ $t("编辑") }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-if="batchEdit"
              size="mini"
              @click="cancel"
            >{{ $t("取消") }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-if="batchEdit"
              v-hasPermi="['anxin:dailyCost:edit']"
              type="primary"
              size="mini"
              @click="batchSaveHandle"
            >{{ $t("保存") }}</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="sysUserDailyCostList" border tooltip-effect="darkTable">
          <el-table-column :label="$t('序号')" type="index" align="center" width="50" />
          <el-table-column :label="$t('用户名称')" align="center" prop="userName" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="link-type" @click="updateHandle(scope.row)">{{ scope.row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('人天成本(元)')" align="center" prop="dailyCost" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="!batchEdit">{{ moneyFormat(scope.row.dailyCost) }}</span>
              <Money v-else v-model="scope.row.dailyCost" :placeholder="$t('人天成本')" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" prop="remark" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="!batchEdit">{{ scope.row.remark }}</span>
              <el-input v-else v-model="scope.row.remark" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
            </template>
          </el-table-column>
          <!--          <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-button-->
          <!--                v-hasPermi="['anxin:dailyCost:view']"-->
          <!--                size="small"-->
          <!--                type="text"-->
          <!--                icon="el-icon-view"-->
          <!--                @click="updateHandle(scope.row)"-->
          <!--              >{{ $t('查看') }}</el-button>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
        </el-table>
      </el-col>
    </el-row>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改系统用户人天成本维护对话框 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <dailyCostList ref="dailyCostList" />
    </el-dialog>

    <!-- 导入 -->
    <el-dialog
      :title="$t('人天成本导入')"
      :visible.sync="upload.open"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport+ '&createTime=' + queryParams.createTime"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('上传') }}</em>
        </div>
        <!--        <div slot="tip" class="el-upload__tip">-->
        <!--          <el-checkbox v-model="upload.updateSupport" /> {{ $t('是否更新已经存在的数据') }}-->
        <!--        </div>-->
        <div slot="tip" class="el-upload__tip" style="color:red">
          {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}
          <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
            {{ $t('下载模板') }}
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSysUserDailyCost, delSysUserDailyCost, batchSaveDailCost } from '@/api/anxin/dailyCost/maintain/sysUserDailyCost'
import { listsDept, treeselect } from '@/api/system/dept'
import dailyCostList from './dailyCostList.vue'
import { getToken } from '@/utils/auth'
export default {
    components: {
        dailyCostList
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          treeLoading: true,
          // 总条数
          total: 0,
          // 系统用户人天成本维护表格数据
          sysUserDailyCostList: [],
          // 部门名称
          deptName: undefined,
          // 部门树选项
          deptOptions: [],
          // 人员状态字典
          statusOptions: [],
          // 要展开的层级
          expandedKeys: [],
          defaultProps: {
            children: 'children',
            label: 'label',
            isLeaf: 'leaf'
          },
          // 弹出层标题
          title: '人天成本维护',
          // 是否显示弹出层
          formOpen: false,
          // 批量编辑
          batchEdit: false,
          // 查询参数
          queryParams: {
              userId: undefined,
              deptId: undefined,
              status: '0',
              createTime: this.getNowFormatDate(),
              pageNum: 1,
              pageSize: 10
          },
          // 查询方式
          type: '',
          // 表单参数
          form: {},
          // 表单校验
          rules: {},
          // 用户导入参数
          upload: {
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: '',
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            updateSupport: 0,
            // 设置上传的请求头部
            headers: { Authorization: 'Bearer ' + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + '/maintain/sysUserDailyCost/importData'
          }
      }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      if (this.type === 'table') {
        if (val) {
          if (this.timer) {
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(() => {
            listsDept({ deptName: val }).then(res => {
              res.data.forEach(item => {
                item.leaf = true
              })
              this.deptOptions = res.data
              this.$refs.tree.root.setData(res.data)
            })
          }, 300)
        } else {
          this.refershTree()
        }
      } else {
        this.$refs.tree.filter(val)
      }
    }
  },
  created() {
      this.getList()
      this.treeLoading = true
      // 获取布局类型
      if (this.$store.state.app.componentLayout) {
        this.$set(this, 'type', this.$store.state.app.componentLayout)
      } else {
        this.type = 'tree'
      }
      // 更新展示的节点名称
      if (this.$store.state.app.componentLayout === 'table') {
        this.defaultProps.label = 'deptName'
      } else {
        this.defaultProps.label = 'label'
      }
      this.treeLoading = false
      this.getTreeselect()
      this.getDicts('sys_normal_disable').then(response => {
        this.statusOptions = response.data
      })
  },
  methods: {
    /** 查询系统用户人天成本维护列表 */
    getList() {
        this.loading = true
        listSysUserDailyCost(this.queryParams).then(response => {
            this.sysUserDailyCostList = response.rows
            this.total = response.total
            this.loading = false
        }).catch(() => {
            this.loading = false
        })
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            userId: undefined,
            dailyCost: undefined,
            startDate: undefined,
            endDate: undefined,
            remark: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined
        }
        this.queryParams = {
            userId: undefined,
            dailyCost: undefined,
            deptId: undefined,
            startDate: this.getNowFormatDate(),
            endDate: undefined,
            pageNum: 1,
            pageSize: 10
        }
        this.resetForm('form')
        this.resetForm('queryParams')
    },
    // 获取当前日期函数
    getNowFormatDate() {
      const date = new Date()
      const year = date.getFullYear() // 获取完整的年份(4位)
      let month = date.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
      if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
      // let strDate = date.getDate() // 获取当前日(1-31)
      // if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
      return `${year}-${month}`
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryParams.createTime = this.getNowFormatDate()
        this.queryHandle()
    },
    /**
     * 批量编辑
     */
    batchEditHandle() {
      this.loading = true
      this.batchEdit = true
      this.loading = false
    },
    /**
     * 批量保存
     */
    batchSaveHandle() {
      this.loading = true
      batchSaveDailCost(this.sysUserDailyCostList).then(response => {
        if (response.code === 200) {
          this.msgSuccess(this.$t('保存成功'))
          this.closeForm()
        } else {
          this.msgError(response.msg)
        }
        this.loading = false
        this.batchEdit = false
      }).catch(() => {
        this.loading = false
        this.batchEdit = false
      })
    },
    /**
     * 取消
     */
    cancel() {
      this.loading = true
      this.getList()
      this.batchEdit = false
      this.loading = false
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
            this.$refs.dailyCostList.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            row.id = row.userId
            this.title = row.userName + '-人天成本维护'
            this.$refs.dailyCostList.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            return delSysUserDailyCost(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(() => {
            this.loading = false
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        this.$confirm(this.$t('是否确认导出数据项?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(() => {
            this.downLoadExcel('/maintain/sysUserDailyCost/export', this.queryParams)
        }).then(response => {
            this.download(response.msg)
        }).catch(() => {
        })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      if (this.type === 'tree') {
        treeselect().then(response => {
          this.deptOptions = response.data
        })
      }
      var query = { 'deptType': 'GS' }
      treeselect(query).then(response => {
        this.companyOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 懒加载部门
    lazyLoad(node, resolve) {
      console.log(node)
      if (node.level === 0) {
        // 加载一级节点
        this.firstNode = node
        this.resolve = resolve
        this.loadFirstNode(resolve)
      }
      if (node.level > 0) {
        this.loadOtherNode(node, resolve)
      }
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.$t('导入')
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 下载模板
    fetchTemplate() {
      const href1 = window.location.href
      const href2 = this.$route.path
      const url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/sysUserDailyCostImportTemplate.xlsx'
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>
